<!-- CommentWall.vue -->
<template>
  <div class="flex h-screen bg-gray-100">
    <!-- 侧边栏 -->
    <aside class="w-70 bg-white shadow-lg fixed h-full">
      <div class="p-6">
        <!-- Logo -->
        <div class="flex items-center space-x-3 mb-8">
          <el-icon class="text-2xl text-purple-600"><ChatLineSquare /></el-icon>
          <h1 class="text-xl font-bold text-gray-800">校园评论墙</h1>
        </div>

        <!-- 分类导航 -->
        <nav class="space-y-2">
          <el-menu
            :default-active="currentCategory"
            class="border-0"
            @select="handleCategoryChange"
          >
            <el-menu-item
              v-for="tag in tagList"
              :key="tag.tagId"
              :index="tag.tagId.toString()"
            >
              <span>{{ tag.tagName }}</span>
            </el-menu-item>
          </el-menu>
        </nav>

        <!-- 用户信息 -->
        <div class="absolute bottom-0 left-0 w-full p-6 border-t">
          <div class="flex items-center space-x-4">
            <el-avatar
              :size="50"
              :src="userInfo.avatar || defaultAvatar"
            />
            <div class="flex-1">
              <div class="text-lg font-semibold">{{ userInfo.username }}</div>
            </div>
          </div>
        </div>
      </div>
    </aside>

    <!-- 主内容区 -->
    <main class="flex-1 ml-70 p-6">
      <!-- 顶部工具栏 -->
      <div class="flex items-center justify-between mb-6">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索评论..."
          class="w-64"
          :prefix-icon="Search"
          @input="handleSearch"
        />
        <div class="flex space-x-4">
          <el-radio-group v-model="sortType" size="large" @change="handleSortChange">
            <el-radio-button label="newest">最新</el-radio-button>
            <el-radio-button label="hottest">最热</el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 评论发布表单 -->
      <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <el-form @submit.prevent="handleSubmit">
          <el-input
            v-model="newComment.content"
            type="textarea"
            :rows="3"
            placeholder="分享你的想法..."
            resize="none"
            maxlength="500"
            show-word-limit
          />
          <div class="flex items-center justify-between mt-4">
            <el-select
              v-model="newComment.tags"
              multiple
              placeholder="选择标签"
              :multiple-limit="3"
            >
              <el-option
                v-for="tag in tagList"
                :key="tag.tagId"
                :label="tag.tagName"
                :value="tag.tagId"
              />
            </el-select>
            <el-button
              type="primary"
              :disabled="!newComment.content || submitting"
              :loading="submitting"
              @click="handleSubmit"
            >
              发布评论
            </el-button>
          </div>
        </el-form>
      </div>

      <!-- 评论列表 -->
      <div v-loading="loading" class="space-y-4">
        <el-empty v-if="shareList.length === 0" description="暂无评论" />
        
        <el-card
          v-for="share in shareList"
          :key="share.shareId"
          class="comment-card hover:shadow-lg transition-shadow"
          @click="navigateToDetail(share.shareId)"
        >
          <div class="flex items-start space-x-4">
            <el-avatar :size="40" :src="getUserAvatar(share)" />
            <div class="flex-1">
              <div class="flex items-center justify-between">
                <div>
                  <span class="font-medium">{{ share.createBy }}</span>
                  <span class="text-gray-500 text-sm ml-2">
                    {{ formatTime(share.createTime) }}
                  </span>
                </div>
                <div>
                  <el-tag
                    v-if="share.tagsId && share.tagsId.length > 0"
                    size="small"
                    type="info"
                  >
                    {{ getTagName(share.tagsId[0]) }}
                  </el-tag>
                </div>
              </div>
              <p class="mt-2 text-gray-700">{{ share.content }}</p>
              <div class="mt-2 text-sm text-gray-500 flex justify-between items-center">
                <div>
                  <span><el-icon class="mr-1"><View /></el-icon>{{ share.viewCount || 0 }}</span>
                  <span class="ml-4"><el-icon class="mr-1"><ChatDotSquare /></el-icon>{{ share.commentCount || 0 }}</span>
                </div>
                <el-button
                  v-if="canDelete(share)"
                  type="danger"
                  size="small"
                  text
                  @click.stop="handleDelete(share.shareId)"
                >删除</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 分页 -->
      <div class="mt-8 flex justify-center">
        <el-pagination
          v-if="total > 0"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ChatLineSquare, Search, View, ChatDotSquare } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { 
  getShareList, 
  getShareByTag, 
  getAllTags,
  addShare,
  deleteShare
} from '@/api/share'
import { useUserStore } from '@/store/user'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const router = useRouter()
const userStore = useUserStore()

// 状态数据
const loading = ref(false)
const submitting = ref(false)
const searchKeyword = ref('')
const sortType = ref('newest')
const currentCategory = ref('')
const shareList = ref([])
const tagList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 新评论表单
const newComment = ref({
  content: '',
  tags: []
})

// 用户信息
const userInfo = computed(() => {
  return {
    userId: userStore.userId,
    username: userStore.username,
    avatar: userStore.avatar || defaultAvatar
  }
})

// 获取用户头像
const getUserAvatar = (share) => {
  // 可以根据实际情况获取用户头像，这里使用默认头像
  return defaultAvatar
}

// 获取标签名称
const getTagName = (tagId) => {
  const tag = tagList.value.find(t => t.tagId === tagId)
  return tag ? tag.tagName : tagId
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).fromNow()
}

// 是否可以删除
const canDelete = (share) => {
  return share.userId === userStore.userId || userStore.isAdmin
}

// 获取分享列表
const fetchShareList = async () => {
  loading.value = true
  try {
    const res = await getShareList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取评论列表失败')
    }
  } catch (error) {
    console.error('获取评论列表失败:', error)
    ElMessage.error('获取评论列表失败')
  } finally {
    loading.value = false
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await getAllTags()
    if (res.code === 0 || res.code === 200) {
      tagList.value = res.data || []
    } else {
      console.error('获取标签列表失败:', res.message)
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 根据标签筛选
const filterByTagId = async (tagId) => {
  if (!tagId) {
    fetchShareList()
    return
  }
  
  loading.value = true
  try {
    const res = await getShareByTag(tagId)
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data || []
      total.value = shareList.value.length
    } else {
      ElMessage.error(res.message || '获取标签分享失败')
    }
  } catch (error) {
    console.error('获取标签分享失败:', error)
    ElMessage.error('获取标签分享失败')
  } finally {
    loading.value = false
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  
  if (!newComment.value.content.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  submitting.value = true
  try {
    const data = {
      userId: userStore.userId,
      createBy: userStore.username,
      content: newComment.value.content,
      tags: newComment.value.tags
    }
    
    const res = await addShare(data)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('发布成功')
      newComment.value = {
        content: '',
        tags: []
      }
      await fetchShareList()
    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败')
  } finally {
    submitting.value = false
  }
}

// 处理分类切换
const handleCategoryChange = (tagId) => {
  currentCategory.value = tagId
  currentPage.value = 1
  filterByTagId(tagId)
}

// 处理排序方式变化
const handleSortChange = () => {
  currentPage.value = 1
  fetchShareList()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchShareList()
}

// 导航到详情页
const navigateToDetail = (shareId) => {
  router.push(`/share/${shareId}`)
}

// 删除评论
const handleDelete = async (shareId) => {
  try {
    await ElMessageBox.confirm('确定要删除这条分享吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteShare(shareId)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('删除成功')
      await fetchShareList()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchShareList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchShareList()
}

onMounted(() => {
  fetchTags()
  fetchShareList()
})

// 监听分类变化
watch(currentCategory, (tagId) => {
  if (tagId) {
    filterByTagId(tagId)
  } else {
    fetchShareList()
  }
})
</script>

<style scoped>
.w-70 {
  width: 280px;
}

.ml-70 {
  margin-left: 280px;
}

.comment-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.comment-card:hover {
  transform: translateY(-2px);
}
</style> 